
// start variables
var geocoder;
var map;
//user marker for map in def pos
var userMarker;
//store markers
//var firstStore_marker;
//var secondStore_marker;
//var thirdStore_marker;
//directions variables
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// first view configuration
var startMapViewZoom = 10; // start zoom for our map
var mapCoordinatesLength = 6; // Latitude & Longitude capasity
// Kiev coordinates (KPI)
var defaultStartLatitude = 50.447892;
var defaultStartLongitude = 30.451584;
//first store coordinates
//    var firstStoreLatitude = 50.518750;
//    var firstStoreLongitude = 30.239783;
//    //second store coordinates
//    var secondStoreLatitude = 50.273889;
//    var secondStoreLongitude = 30.372222;
//    //third store coordinates
//    var thirdStoreLatitude = 50.511083;
//    var thirdStoreLongitude = 30.790900;

function initialize() {

    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();

    var mapOptions = {
        zoom: startMapViewZoom,
        center: new google.maps.LatLng(defaultStartLatitude, defaultStartLongitude),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('sideLeft'), mapOptions);
    directionsDisplay.setMap(map);

    // creates a draggable marker to the given coords
    userMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(defaultStartLatitude, defaultStartLongitude),
        draggable: true,
        animation: google.maps.Animation.DROP,
        title: 'Customer'
    });

    // creates a nondraggable marker for first shop
//      firstStore_marker = new google.maps.Marker({
//            map:map,
//            position: new google.maps.LatLng(firstStoreLatitude, firstStoreLongitude),
//            draggable:false,
//            icon:  'http://google-maps-icons.googlecode.com/files/factory.png',
//            animation: google.maps.Animation.DROP,
//            title : 'First store'
//      });

    // creates a nondraggable marker for second shop
//      secondStore_marker = new google.maps.Marker({
//            map:map,
//            position: new google.maps.LatLng(secondStoreLatitude, secondStoreLongitude),
//            draggable:false,
//            icon:  'http://google-maps-icons.googlecode.com/files/factory.png',
//            animation: google.maps.Animation.DROP,
//            title : 'Second store'
//      });

    // creates a nondraggable marker for third shop
//      thirdStore_marker = new google.maps.Marker({
//            map:map,
//            position: new google.maps.LatLng(thirdStoreLatitude, thirdStoreLongitude),
//            draggable:false,
//            icon:  'http://google-maps-icons.googlecode.com/files/factory.png',
//            animation: google.maps.Animation.DROP,
//            title : 'Third store'
//      });

    // adds a animation listener to the marker
    google.maps.event.addListener(userMarker, 'click', toggleBounce);
    // adds a animation listener to the store marker
//      google.maps.event.addListener(firstStore_marker, 'click', toggleBounceSO);
    // adds a animation listener to the second store marker
//      google.maps.event.addListener(secondStore_marker, 'click', toggleBounceSS);
    // adds a animation listener to the third store marker
//      google.maps.event.addListener(thirdStore_marker, 'click', toggleBounceST);

    // adds a listener to the marker
    // gets the coords when drag event ends
    // then updates the input with the new coords
//    google.maps.event.addListener(userMarker, 'dragend', function(evt) {
//        document.getElementById('latitude').value = evt.latLng.lat().toFixed(mapCoordinatesLength);
//        document.getElementById('longitude').value = evt.latLng.lng().toFixed(mapCoordinatesLength);
//    });
}
// search customer address
function codeAddress(address, callback) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results);
//            setMarkerPosition(results, 0);
        } else {
            console.log("Geocode was not successful: " + status);
        }
    });
}

function setMarkerPosition(results, index) {
    map.setCenter(results[index].geometry.location);
    userMarker.setPosition(results[index].geometry.location);
    var latitude = userMarker.position.lat();
    var longitude = userMarker.position.lng();
    document.getElementById('latitude').value = latitude.toFixed(mapCoordinatesLength);
    document.getElementById('longitude').value = longitude.toFixed(mapCoordinatesLength);
}
;

// animation function
function toggleBounce() {
    if (userMarker.getAnimation() != null) {
        userMarker.setAnimation(null);
    } else {
        userMarker.setAnimation(google.maps.Animation.BOUNCE);
    }
}
// animation function for first store
function toggleBounceSO() {
    if (firstStore_marker.getAnimation() != null) {
        firstStore_marker.setAnimation(null);
    } else {
        firstStore_marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}
// animation function for second store
function toggleBounceSS() {
    if (secondStore_marker.getAnimation() != null) {
        secondStore_marker.setAnimation(null);
    } else {
        secondStore_marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}
// animation function for third store
function toggleBounceST() {
    if (thirdStore_marker.getAnimation() != null) {
        thirdStore_marker.setAnimation(null);
    } else {
        thirdStore_marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}

//calculates distance between two points in km's
function calcDistance(p1, p2) {
    return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(4);
}

function calcRoute() {

    var firstToUser = calcDistance(userMarker.getPosition(), firstStore_marker.getPosition());
    var secondToUser = calcDistance(userMarker.getPosition(), secondStore_marker.getPosition());
    var thirdToUser = calcDistance(userMarker.getPosition(), thirdStore_marker.getPosition());

    var first = {"Position": firstStore_marker.getPosition(), "Length": firstToUser};
    var second = {"Position": secondStore_marker.getPosition(), "Length": secondToUser};
    var third = {"Position": thirdStore_marker.getPosition(), "Length": thirdToUser};

    var shortestWay = first;
    //fill shortest way object
    if (shortestWay.Length > second.Length) {
        shortestWay = second;
    } else if (shortestWay.Length > third.Length) {
        shortestWay = third;
    }

    // need cacl start
    var start = shortestWay.Position;
    // end - user position
    var end = userMarker.getPosition();
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    document.getElementById('distance').value = shortestWay.Length;
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}
google.maps.event.addDomListener(window, 'load', initialize);